package com.lsy.jetpackdemo

import android.bluetooth.le.TransportBlock
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import java.lang.Exception

/**
 * @Author Lsy
 * @Date 2022/10/12 10:09
 */
open class BaseViewModel : ViewModel() {
    private val error by lazy { SingleLiveEvent<Exception>() }
    private val finally by lazy { SingleLiveEvent<Int>() }

    fun launchUI(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch {
        try {
            withTimeout(30 * 1000) {
                block()
            }
        } catch (e: Exception) {
            error.value = e
        } finally {
            finally.value = 200
        }
    }

    fun getError(): LiveData<Exception> = error
    fun getFinally(): LiveData<Int> = finally

}